package com.cgwx.tmservice.config.mybatisplus;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.handler.TableNameHandler;
//import com.baomidou.mybatisplus.extension.plugins.inner.DynamicTableNameInnerInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.*;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.Map;

/**
 * @author GaoWei
 * @Date 2023/9/2 - 15:00
 */
@Configuration
@MapperScan("com.cgwx.tmservice.mapper")
public class MybatisPlusConfig {
    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        // 动态表名插件
        DynamicTableNameInnerInterceptor dynamicTabNameInterceptor = new DynamicTableNameInnerInterceptor();
        Map<String, TableNameHandler> tableNameHandlerMap = new HashMap<>();
        tableNameHandlerMap.put("tm_info_log_date", (sql, tableName) -> {
            String requestTableName = RequestDynamicTableNameHelper.getRequestData();
//            System.out.println(requestTableName);
            // 如果不为空，使用动态表名。
            if(StringUtils.isNotBlank(requestTableName)){
                RequestDynamicTableNameHelper.remove();
                return requestTableName;
            }
            return tableName;
        });
        tableNameHandlerMap.put("tm_info_his_date", (sql, tableName) -> {
            String requestTableName = RequestDynamicTableNameHelper.getRequestData();
//            System.out.println(requestTableName);
            // 如果不为空，使用动态表名。
            if(StringUtils.isNotBlank(requestTableName)){
                RequestDynamicTableNameHelper.remove();
                return requestTableName;
            }
            return tableName;
        });
        dynamicTabNameInterceptor.setTableNameHandlerMap(tableNameHandlerMap);
        interceptor.addInnerInterceptor(dynamicTabNameInterceptor);
        return interceptor;
    }

//    批量插入插件
    @Bean
    public InsertBatchSqlInjector easySqlInjector() {
        return new InsertBatchSqlInjector();
    }
}
